<!--  -->
<template>
  <el-upload
    class="upload-demo"
    action="https://jsonplaceholder.typicode.com/posts/"
    :on-change="handleChange"
    :file-list="fileList"
    :show-file-list="showFileList"
    :limit="limit"
    :http-request="handleRequest"
  >
    <div>
      <slot />
      <slot v-if="isShowTip" name="tip" />
    </div>
  </el-upload>
</template>

<script>
  import { apiUploadImage } from './api'

  export default {
    components: {},
    props: {
      imgList: { type: Array, default: () => [] }, //  上传列表
      isShowTip: { type: Boolean, default: false }, // 是否展示提示信息
      showFileList: { type: Boolean, default: false }, //  是否展示图片列表（element选项）
      limit: { type: Number, default: 5 }, //  图片限制几张
      limitSize: { type: Number, default: 500 } // 图片限制大小单位kb  默认500kb
    },
    data() {
      return {
        fileList: []
      }
    },
    watch: {
      imgList: {
        immediate: true,
        deep: true,
        handler: function(value) {
          if (Array.isArray(value)) {
            this.fileList = value.map(item => ({ name: item, url: this.$tools.handleImage(item) }))
          }
        }

      }
    },
    methods: {
      handleChange(file, fileList) {
        this.$emit('change', fileList)
      },

      async handleRequest({ file }) {
        const isLimit = file.size / 1024 < this.limitSize

        if (!isLimit) {
          this.$message.error(`上传头像图片大小不能超过 ${this.limitSize}KB!`)
          return false
        }

        const formData = new FormData()
        formData.append('file', file)
        const res = await apiUploadImage(formData)
        this.$message.success('上传成功！')
        this.fileList.push({ name: res.fileName, url: this.$tools.handleImage(res.id), fileId: res.id })
        this.$emit('success', this.fileList)
      }
    }

  }
</script>
<style lang="scss" scoped></style>
